package com.aikg.kgrag_java.service;

import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import net.sourceforge.tess4j.Tesseract;
import net.sourceforge.tess4j.TesseractException;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * @Author tfan
 * @Description
 * @Date 2024/12/31 11:56
 **/
@Service
@Slf4j
@AllArgsConstructor
public class OcrService {

    private final Tesseract tesseract;

    /**
     * 识别图片中的文字
     *
     * @param imageFiles 图片文件
     * @return 文字信息
     */
    public String recognizeText(MultipartFile[] imageFiles){

        StringBuilder result = new StringBuilder();
        try {
            for (MultipartFile imageFile : imageFiles) {
                // 转换
                InputStream sbs = new ByteArrayInputStream(imageFile.getBytes());
                BufferedImage bufferedImage = ImageIO.read(sbs);

                // 对图片进行文字识别
                result.append(tesseract.doOCR(bufferedImage));
            }
        } catch (IOException | TesseractException e) {
            throw new RuntimeException(e);
        }
        return result.toString();
    }
}